package com.tomtop.core.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.tomtop.config.WebSiteConfig;
import com.tomtop.core.Context;
import com.tomtop.core.logging.RunTimeLog;

/**
 * 记录收到的http请求.
 * 
 * @author Administrator
 *
 */
@Component
public class LoggerInterceptor extends HandlerInterceptorAdapter {
	private final static Logger logger = LoggerFactory.getLogger(LoggerInterceptor.class);

	@Override
	public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler) throws Exception {
		String url = request.getRequestURI();
		Context.init(request, response);
		if (filterLogger(url)) {
			logger.debug("已接受到请求:{}" , url);
			Context.sendUserId();
			return true;
		}
		logger.info("资源{}不允许访问，即将转至首页!",url);
		return false;
	}
	
	private boolean filterLogger(final String url) {
		return (url.isEmpty() || url.indexOf('.') == -1 || url.endsWith(".do") || url.endsWith(".json"));
	}

	@Override
	public void postHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler, final ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}

	@Override
	public void afterCompletion(final HttpServletRequest request, final HttpServletResponse response,final Object handler, final Exception ex) throws Exception {
		String url = request.getRequestURI();
		if (!filterLogger(url))
			return;
		long runtime = (System.currentTimeMillis() - Context.getBeginTime());
		RunTimeLog.log(runtime, "请求已结束:{}, 请求总共耗时{}毫秒", url,runtime);
		if (ex != null)
			logger.error("请求出错" + url, ex);
		if(WebSiteConfig.isContain()){ 
			response.addHeader("Access-Control-Allow-Origin", request.getScheme()+"//"+Context.getHost());
			response.addHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
			response.addHeader("Access-Control-Allow-Headers", "Content-Type");
		}
		Context.remove();
	}
}